﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Text;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Openfree.Framework.DataAccess;

public partial class StockOutManager : PMSBase
{ 
    private SqlCodeConfig codeConfig;
    string cmdText = "SELECT T.*,A.CodeName AS StockOutTypeName" + PMSAccess.AppendSql_UserOrg + " FROM {0} T  LEFT JOIN " + SqlCodeConfig.TableName + " A ON A.CodeValue=T.StockOutType AND A.Category='" + PMSCodeCategory.PMS_CKLX + "' where 1=1 ";
    protected void Page_Load(object sender, EventArgs e)
    {
        this.TableName = "IC_StockOut";
        this.Key = "StockOutID";
        if (!IsPostBack)
        {
            pnlGrid.Visible = true;
            pnlEdit.Visible = false;
            string sql = string.Format(cmdText+" ORDER BY T.CREATETIME DESC", this.TableName);
            FillGirdView(0, sql);
            InitLoadData();
            if (!string.IsNullOrEmpty(Request["StockOutID"]))
            {
                this.btnView_Click(null, e);
            }
        }
        else
        {
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
        }
    }
    private void InitLoadData()
    {
        codeConfig = new SqlCodeConfig(this.Connection);
        DataSet ds = codeConfig.LoadDataByCategory(PMSCodeCategory.PMS_CKLX);
        this.BindDropDownList(S_StockOutType, ds, true);
        this.BindDropDownList(P_StockOutType, ds, true);
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        StringBuilder sql = new StringBuilder(string.Format(cmdText, this.TableName));
        if (!string.IsNullOrEmpty(S_StockOutCode.Text))
        {
            sql.Append(" AND T.StockOutCode like '%").Append(S_StockOutCode.Text).Append("%'");
        }
        if (!string.IsNullOrEmpty(S_StockOutDate.Text))
        {
            sql.Append(" AND T.StockOutDate = '").Append(S_StockOutDate.Text).Append("'");
        }
        if (!string.IsNullOrEmpty(S_StockOutType.SelectedValue))
        {
            sql.Append(" AND T.StockOutType = '").Append(S_StockOutType.SelectedValue).Append("'");
        }
        sql.Append(" ORDER BY T.CREATETIME DESC");
        FillGirdView(0, sql.ToString());
    }
    protected void FillGirdView(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "cmdText"].ToString();
        }
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        splitPage.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        //成功查询出数据后缓存
        ViewState[this.ClientID + "cmdText"] = cmdText;
        gridView.ShowFooter = true;
        gridView.NavigationData = splitPage.GetNavigationData(currentPage);
        gridView.DataSource = ds.Tables[0];
        gridView.DataBind();
    }

    protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((HyperLink)e.Row.Cells[1].Controls[0]).NavigateUrl = "StockOutManager.aspx?StockOutID=" + ((HiddenField)e.Row.Cells[0].Controls[1]).Value;
            e.Row.Cells[2].Text = this.ParseDateToShort(e.Row.Cells[2].Text);
            e.Row.Cells[6].Text = this.ParseDateToShort(e.Row.Cells[6].Text);
        }
    }

    protected void gridView_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        FillGirdView(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "cmdText"].ToString());
    }
     
    /// <summary>
    /// 清空控件，清空指定的TextBox、Label
    /// </summary>
    private void ResetComponent()
    {
        hfStockOutID.Value = string.Empty;
        this.ClearPrexControlValues(this.DefaultPrex);
        P_LoginName.Text = SessionManager.Username;
        P_Department.Text = SessionManager.OrgName;
    }


    protected void btnAdd_Click(object sender, EventArgs e)
    {
        hfAddOrEdit.Value = "Add";
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        btnSelect.Visible = true;
        btnSave.Visible = true;
        ResetComponent();
        SetReadOnly(this.DefaultPrex, false);
        P_LoginName.ReadOnly = true;
        P_Department.ReadOnly = true;
        DataSet ds = PMSAccess.GetDataSet(this.Connection,"select * from " + this.TableName + " where 1=2 ", this.TableName);
        SessionManager.DataSet = ds;
        GoodItems.IsReadOnly = false;
        GoodItems.InitData("IC_StockOutItem", "StockOutItemID", "StockOutID", System.Guid.NewGuid().ToString());
    }


    protected void btnRemove_Click(object sender, EventArgs e)
    {
        string stockOutID = Request.Form["StockOutID"];
        if (string.IsNullOrEmpty(stockOutID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        base.WriteLog("出库单", "删除出库单'" + stockOutID + "'!",
            LogType.Warning, this.GetType().ToString());
        PMSAccess.RemoveDataRow(this.TableName, this.Key, stockOutID);
        PMSAccess.RemoveDataRow("IC_StockOutItem", this.Key, stockOutID);
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }

    protected void btnEdit_Click(object sender, EventArgs e)
    {
        string stockOutID = Request.Form["StockOutID"];
        if (string.IsNullOrEmpty(stockOutID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        hfAddOrEdit.Value = "Edit";
        hfStockOutID.Value = stockOutID;
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        btnSelect.Visible = true;
        btnSave.Visible = true;
        SetReadOnly(this.DefaultPrex, false);
        P_LoginName.ReadOnly = true;
        P_Department.ReadOnly = true;
        string sql = string.Format(cmdText + " AND T.StockOutID='" + stockOutID + "' ", this.TableName);
        DataSet ds = PMSAccess.GetDataSet(this.Connection, sql, this.TableName); 
        SessionManager.DataSet = ds;
        DataRow dr = ds.Tables[this.TableName].Rows[0];
        this.FillValueByPrexFromDataRow(dr, this.DefaultPrex);
        P_LoginName.Text = dr["UserName"].ToString();
        P_Department.Text = dr["OrgName"].ToString();

        GoodItems.IsReadOnly = false;
        GoodItems.InitData("IC_StockOutItem", "StockOutItemID", "StockOutID", stockOutID);

    }

    protected void btnView_Click(object sender, EventArgs e)
    {
        string stockOutID = Request.Form["StockOutID"];
        if (sender==null)
            stockOutID = Request["StockOutID"];
        if (string.IsNullOrEmpty(stockOutID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        hfAddOrEdit.Value = "View";
        hfStockOutID.Value = stockOutID;
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        SetReadOnly(this.DefaultPrex, true);
        string sql = string.Format(cmdText + " AND T.StockOutID='" + stockOutID + "' ", this.TableName);
        DataSet ds = PMSAccess.GetDataSet(this.Connection, sql, this.TableName);  
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        btnSelect.Visible = false;
        btnSave.Visible = false;
        SessionManager.DataSet = ds;
        DataRow dr = ds.Tables[this.TableName].Rows[0];
        this.FillValueByPrexFromDataRow(dr, this.DefaultPrex);
        P_LoginName.Text = dr["UserName"].ToString();
        P_Department.Text = dr["OrgName"].ToString();
        GoodItems.IsReadOnly = true;
        GoodItems.InitData("IC_StockOutItem", "StockOutItemID", "StockOutID", stockOutID);

    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        pnlGrid.Visible = true;
        pnlEdit.Visible = false;
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (hfAddOrEdit.Value == "Add")
        {
            ExecuteAdd(); 
        }
        else
        {
            ExecuteEdit();
        }
    }

    private void ExecuteAdd()
    {
        if (GoodItems.PreProcessSave())
        {
            DataRow dr = SessionManager.DataSet.Tables[this.TableName].NewRow();
            dr["StockOutID"] = System.Guid.NewGuid().ToString();
            dr["StockOutCode"] = PMSAccess.GetCode(EnumCodeKind.ChuKu);
            hfStockOutID.Value = dr["StockOutID"].ToString();
            this.FillDataRowByPrex(ref dr, this.DefaultPrex, EnumOperator.ADD);
            dr["Status"] = StockOutStatus.UnBack;
            dr["LoginName"] = SessionManager.UserID;
            dr["Department"] = SessionManager.OrgID;
            SessionManager.DataSet.Tables[this.TableName].Rows.Add(dr);
            foreach (DataRow _dr in SessionManager.DataSet.Tables["IC_StockOutItem"].Rows)
            {
                _dr["StockOutID"] = hfStockOutID.Value;
            } 
            PMSAccess.UpdateDataSet(this.Connection, new string[] { "IC_StockOut", "IC_StockOutItem" }, SessionManager.DataSet);
            ResetComponent();
            SessionManager.DataSet.Tables.Remove("IC_StockOutItem");
            GoodItems.InitData("IC_StockOutItem", "StockOutItemID", "StockOutID", hfStockOutID.Value);
            base.Alert("新建成功");
        }
    }


    private void ExecuteEdit()
    {
        if (GoodItems.PreProcessSave())
        {
            DataSet ds = PMSAccess.GetDataSet(this.TableName, this.Key, hfStockOutID.Value);
            DataRow dr = ds.Tables[0].Rows[0];
            this.FillDataRowByPrex(ref dr, this.DefaultPrex, EnumOperator.EDIT);
            dr["LoginName"] = SessionManager.UserID;
            dr["Department"] = SessionManager.OrgID;

            PMSAccess.UpdateDataSet(this.Connection, new string[] { "IC_StockOut", "IC_StockOutItem" }, SessionManager.DataSet);
            base.Alert("修改成功");
        }
    }
    public void btnSelect_Click(object sender, EventArgs e)
    {
        if (GoodItems.OnSelect != null)
            GoodItems.OnSelect(sender, e);
    } 
}
